package com.siyu.service;

import com.luhuiguo.fastdfs.service.FastFileStorageClient;
import com.siyu.dao.FileRepository;
import com.siyu.model.Files;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class FileService {

    @Autowired
    private FileRepository fileRepository;

    @Autowired
    public FastFileStorageClient storageClient;

    public void uploadFile(MultipartFile file, Long userId) throws IOException {
        String fileUrl = String.valueOf(storageClient.uploadFile(null,file.getInputStream(), file.getSize(),file.getName()));
        Files fileEntity = new Files();
        fileEntity.setFileName(file.getOriginalFilename());
        fileEntity.setFileUrl(fileUrl);
        fileEntity.setFileSize(file.getSize());
        fileEntity.setUserId(Integer.parseInt(String.valueOf(userId)));
        fileRepository.save(fileEntity);
    }

    public byte[] downloadFile(Long fileId) throws IOException {
        Files file = fileRepository.findById(fileId).orElseThrow(() -> new RuntimeException("File not found"));
        return storageClient.downloadFile("group1", file.getFileUrl());
    }

    public List<Files> getSharedFiles(Long userId) {
        return fileRepository.findByUserId(String.valueOf(userId));
    }
}